package com.pdd.mall.controller;

import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.BalanceOperationParam;
import com.pdd.mall.entity.User;
import com.pdd.mall.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 余额管理控制器
 */
@RestController
@RequestMapping("/user/balance")
public class BalanceController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取用户余额
     */
    @GetMapping
    public CommonResult<Map<String, Object>> getUserBalance() {
        Long userId = getCurrentUserId();
        BigDecimal balance = userService.getUserBalance(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("balance", balance);
        
        return CommonResult.success(result);
    }
    
    /**
     * 充值/提现
     */
    @PostMapping("/operate")
    public CommonResult<Map<String, Object>> operateBalance(@RequestBody @Valid BalanceOperationParam param) {
        Long userId = getCurrentUserId();
        BigDecimal newBalance = userService.operateBalance(userId, param);
        
        if (newBalance == null) {
            if (param.getType() == 2) {
                return CommonResult.failed("余额不足");
            } else {
                return CommonResult.failed("操作失败");
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("balance", newBalance);
        
        return CommonResult.success(result);
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/pay/{orderNo}")
    public CommonResult<String> payOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        boolean success = userService.payOrder(userId, orderNo);
        
        if (success) {
            return CommonResult.success("支付成功");
        } else {
            return CommonResult.failed("支付失败，余额不足或订单状态不正确");
        }
    }
    
    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        return user.getId();
    }
}
